<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 *  微信公众平台PHP-SDK, Codeigniter实例
 *  @author nigelvon@gmail.com
 *  @link https://github.com/dodgepudding/wechat-php-sdk
 *  usage:
 *  $this->load->library('CI_Wechat');
 *  $this->ci_wechat->valid();
 *  ...
 *
 */
require_once(APPPATH . 'third_party/wechat-php-sdk/wechat.class.php');

class CI_Wechat extends Wechat {

    protected $_CI;

    public function __construct() {
        $this->_CI = & get_instance();
        $this->_CI->config->load('wechat');
        $options = $this->_CI->config->item('wechat');
        $options['logcallback'] = 'log';
        $this->_CI->load->driver('cache');

        parent::__construct($options);
    }

    /**
     * 重载设置缓存
     * @param string $cachename
     * @param mixed $value
     * @param int $expired
     * @return boolean
     */
    protected function setCache($cachename, $value, $expired) {
        return $this->_CI->cache->file->save($cachename, $value, $expired);
    }

    /**
     * 重载获取缓存
     * @param string $cachename
     * @return mixed
     */
    protected function getCache($cachename) {
        return $this->_CI->cache->get($cachename);
    }

    /**
     * 重载清除缓存
     * @param string $cachename
     * @return boolean
     */
    protected function removeCache($cachename) {
        return $this->_CI->cache->delete($cachename);
    }

    /**
     * 判断是当前环境是否为微信内置浏览器
     * @return boolean
     */
    public function isWeixinBrowser() {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
    }

    /**
     * 获取当前访问的完整url
     * 如 http://benefit.lovchun.com/benefit/index
     * @return string
     */
    public function getCurUrl() {
        $url = 'http://';
        if (isset($_SERVER ['HTTPS']) && $_SERVER ['HTTPS'] == 'on') {
            $url = 'https://';
        }
        if ($_SERVER ['SERVER_PORT'] != '80') {
            $url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI'];
        } else {
            $url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
        }
        return $url;
    }

    /**
     * 跳转至OAuth2.0授权页面
     * 用户点击确认授权后
     * 跳转至上一步所点击的url
     */
    public function redirectOAuth() {
        // OAuth2.0授权
        //$isWeixinBrowser = $this->isWeixinBrowser();
		$isWeixinBrowser = TRUE;
        if ($isWeixinBrowser) {
//            $callback = $this->getCurUrl();
            $callback = 'http://benefit.lovchun.com/benefit/checkCode';
            $redirect_url = $this->getOauthRedirect($callback);
            redirect($redirect_url);
        }
    }

    /**
     * 初始化OAuth
     * 获取粉丝的用户详情
     * @return Array
     * 
      [
      "openid"=>" OPENID",
      " nickname"=> NICKNAME,
      "sex"=>"1",
      "province"=>"PROVINCE"
      "city"=>"CITY",
      "country"=>"COUNTRY",
      "headimgurl"=>"http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ
      4eMsv84eavHiaiceqxibJxCfHe/46",
      "privilege"=>[ "PRIVILEGE1" "PRIVILEGE2"],
      "unionid"=>"o6_bmasdasdsad6_2sgVt7hMZOPfL"
      ]
     */
    public function initOAuth() {
        // 拿到code
        // 换取AcessToken
        $data = $this->getOauthAccessToken();
        // 保存openid至session中
        $openid = $this->get_openid($data['openid']);
        $info = $this->getOauthUserinfo($data['access_token'], $openid);
        return $info;
    }

    public function get_openid($openid = NULL) {

        if ($openid !== NULL) {
            $this->_CI->session->set_userdata('openid', $openid);
        }

        $openid = $this->_CI->session->userdata('openid');

        if (empty($openid)) {
            $this->redirectOAuth();
            exit();
        }

        return $openid;
    }

    /**
     * 记录日志
     * ./application/log/logs.txt
     * @param type $text
     */
    public function log($text) {
        $text = is_array($text) ? serialize($text) : $text;
        $time = date('Y-m-d H:i:s', time());
        $dividingLine = '=========================================';
        file_put_contents(APPPATH . '/logs/log.txt', $text . "\n" . $time . "\n" . $dividingLine . "\n", FILE_APPEND);
    }

}

/* End of file CI_Wechat.php */
/* Location: ./application/libraries/CI_Wechat.php */
